<template>
<div class="wrap">
    <div class="option">
        <Upload  @upload="submitAvatar" :src="src" style="width: 150px;height: 150px;font-size: 100px;"/>
        <h3>{{ usernameHandle }}</h3>
        <div class="tabs">
            <span @click="active ='1'" :class="{active: active === '1'}">基本信息</span>
            <span @click="active ='2'" :class="{active: active === '2'}">修改密码</span>
        </div>
    </div>
    <div class="userinfo">
                <div class="editInfo" v-if="active === '1'" id="editInfo">
                   <div class="item" v-for="item in userinfo">
                        <label class="label">{{ item.key }}</label>
                        <div class="value" v-show="item.show" @click="toogle(item)">{{ item.value }}</div>
                        <el-input @change="change" v-model="(userForm as any)[item.keyStr]" v-if="!item.show" @blur="toogle(item)"></el-input>
                   </div>
                   <div class="item">
                    <el-button type="primary" @click="submit">提 交</el-button>
                   </div>
                </div>
                 <div class="editPassword" v-if="active === '2'">
                    <div class="item">
                        <label class="label">旧密码</label>
                        <el-input  @change="validate" type="password" placeholder="请输入旧密码" show-password v-model="modifyPassword.oldPassword"></el-input>
                   </div>
                   <div class="item">
                        <label class="label">新密码</label>
                        <el-input  @change="validate" type="password" placeholder="请输入新密码" show-password v-model="modifyPassword.newPassword"></el-input>
                   </div>
                   <div class="item">
                        <label class="label">再次输入</label>
                        <el-input @change="validate" type="password" placeholder="请再次输入旧密码" show-password v-model="modifyPassword.newPassword2"></el-input>
                   </div>
                   <div class="item">
                    <el-button :disabled="!showSubmit" type="primary" @click="submitPassword">提 交</el-button>
                   </div>
                </div>
    </div>
</div>
</template>

<script lang='ts' setup>
import Upload from "@/components/Action/upload/index.vue"
import { updateUser} from "@/api/system/user"
import { useSystem } from "@/pinia";
import { computed, nextTick, ref } from "vue";
import {User} from "@/types/user"
import { handleResponse } from "@/utils/responseCode";
import { ElMessage } from "element-plus";
const SystemStore = useSystem()
let active = ref<"1" | "2">("1")
let loading = ref<boolean>(true)
// 处理图片地址
let src = computed(()=>{
    return import.meta.env.VITE_BASEURL +  SystemStore.userinfo?.avatar as string
})
// 处理用户名称
let usernameHandle = computed(() =>{
    
    if (SystemStore.userinfo?.nickname && SystemStore.userinfo.nickname !== "") {
        return SystemStore.userinfo?.nickname
    }
    return SystemStore.userinfo?.username
})
// 映射key
let UserInfoEnum:any = {
    username:"账号",
    nickname:"昵称",
    telephone:"电话",
    email:"邮箱",
    idnumber:"身份证",
    gender:"性别",
}
// 获取key和value
const handleInfo = ():UserEnum[] | [] =>{
    if (!userForm.value) return []
    let arr:UserEnum[] = []
    for (const [k,v] of Object.entries(userForm.value)) {
        UserInfoEnum[k] && arr.push({
            key:UserInfoEnum[k],
            keyStr:k,
            value:v,
            show:true
       })
    }
    return arr
}

let userForm = ref<User.UserInfo>(JSON.parse(JSON.stringify(SystemStore.userinfo)))

interface UserEnum {
    key:keyof User.UserInfo,
    value:any
    show:boolean,
    keyStr:string
}
let userinfo= ref<UserEnum[]>(handleInfo())

const toogle = (item:any) => {
    if (item.keyStr === 'username') return
    item.show = !item.show
  nextTick(()=>{
    let input =  document.querySelectorAll("#editInfo .el-input__inner")  as NodeListOf<HTMLInputElement>
        input[0] && input[0].focus()
  })
}

let modifyPassword = ref({
    oldPassword:"",
    newPassword:"",
    newPassword2:""
})

const change = () =>{
    userinfo = ref<UserEnum[]>(handleInfo())
}
let showSubmit =  ref(false)
const validate = () =>{
    const {oldPassword:op,newPassword:np,newPassword2:np2} = modifyPassword.value
    if (np === "" || np2 === "") return showSubmit.value = false
    if (np !== np2) {
        showSubmit.value = false
      return  ElMessage.error("两次输入密码不一致")
    }
    if (op !=="" && np === np2) {
        showSubmit.value = true
    }
}
// 提交
const submit = async () =>{
    loading.value = true
    try {
        let res = await updateUser(userForm.value)
        const {code,msg} =  res.data
        if (!handleResponse(code,msg)) return loading.value = false
        ElMessage.success("修改成功")
        loading.value = false
        SystemStore.$patch({
            userinfo:userForm.value
        })
    } catch (error) {
        handleResponse("500","服务器异常")
        loading.value = false
    }
}
// 修改密码
const submitPassword = async () =>{
    validate()
    if (!showSubmit.value) return
    const {oldPassword,newPassword} = modifyPassword.value
    let obj:User.Password = {
        type:"password",
        _id:SystemStore.userinfo?._id as string,
        oldPassword,
        newPassword,
    }
    let res = await updateUser(obj)
    const {code,msg} = res.data
    if (!handleResponse(code,msg)) return
    ElMessage.success("密码修改成功")
}
// 修改头像
const submitAvatar = async (file:File) =>{
    loading.value = true
    let form = {
        type:"avatar",
        _id:SystemStore.userinfo?._id,
        avatar:file,
        status:SystemStore.userinfo?.status as boolean,
        username:SystemStore.userinfo?.username as string
    }
    if (form._id && form.avatar && form.status && form.username){
        let res = await updateUser(form)
        const {code,msg,data} =res.data
        if (!handleResponse(code,msg))   return ElMessage.error("头像修改失败")
        ElMessage.success("头像修改成功")
        // 同步更改数据
        SystemStore.userinfo!.avatar = data
    }
    loading.value = false
   
}
nextTick(()=>{
    loading.value = false
})

</script>

<style lang="less" scoped>
.wrap {
    background-color: var(--background);
    display: flex;
    .option {
        width: 200px;
        height: 100%;
        display: flex;
        align-items: center;
        flex-direction: column;
        padding-top: 50px;
        h3 {
            letter-spacing: 10px;
            font-size: 20px;
        }
        .tabs {
            display: flex;
            flex-direction: column;
            width: 100%;
            span {
                font-size: 16px;
                height: 35px;
                line-height: 35px;
                text-align: center;
                cursor: pointer;
                transition: all .3s;
                &:hover {
                    color: var(--active-color);
                }
            }
        }
    }
    .userinfo {
        flex: 1;
        height: 100%;
        padding: 0px 10%;
        display: flex;
        align-items: center;
        justify-content: center;
        .editInfo,.editPassword {
            display: flex;
            flex-direction: column;
            width: 80%;
        }
        .item {
                display: flex;
                align-items: center;
                label {
                    min-width: 100px;
                    width: 100px;
                    height: 36px;
                    line-height: 36px;
                }
                .value {
                    flex: 1;
                    height: 36px;
                    line-height: 36px;
                    cursor: pointer;
                    transition: all .3s;
                    position: relative;
                    &::before {
                        content: "";
                        position: absolute;
                        left: 0px;
                        bottom: 0px;
                        width: 100%;
                        height: 2px;
                        background-color: var(--color);
                    }   
                    &::after {
                        content: "";
                        position: absolute;
                        left: 0px;
                        bottom: 0px;
                        width: 0px;
                        height: 2px;
                        background-color: var(--active-color);
                        transition: all .3s;
                    }   
                    &:hover {
                        &::after {
                            width: 100%;
                        }
                    }
                }
                .el-button{
                    margin:0px auto;
                }
            }
            .item+.item {
                margin-top: 20px;
            }
    }
}
.active {
    color: var(--active-color);
    font-size: 20px!important;
    font-weight: bold;
}
</style>